package common.code;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLConnection;
import java.util.Properties;
import java.util.Scanner;
 
public class URLTest {
 // 一个public方法，返回字符串，错误则返回"error open url"
 public static String getContent(String strUrl) {
  try {
   URL url = new URL(strUrl);
   BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
   String s = "";
   StringBuffer sb = new StringBuffer("");
   while ((s = br.readLine()) != null) {
	   sb.append(s + "/r/n");
   }
   br.close();
   String[] htmls = sb.toString().split("/r/n");
   String path = "images/null.jpg";
   for (int i = 0; i < htmls.length; i++) {
	   if(htmls[i].trim().equals("<div class=\"cardetail-pic\">")){
		   path = htmls[i+2];
	    }
   }
   return path;
  } catch (Exception e) {
   return "error";
  }
 }
 
 public static void initProxy(String host, int port, final String username,
   final String password) {
  Authenticator.setDefault(new Authenticator() {
   protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(username,
      new String(password).toCharArray());
   }
  });
  System.setProperty("http.proxyType", "4");
  System.setProperty("http.proxyPort", Integer.toString(port));
  System.setProperty("http.proxyHost", host);
  System.setProperty("http.proxySet", "true");
 }
 
 public static void main(String[] args) throws IOException {
	Scanner sc = new Scanner(System.in);

	System.out.println("这里输入编号：");
	String number = sc.next();
	//主要部分 start
	String url = "http://www.autohome.com.cn/spec/" + number;
	String path = URLTest.getContent(url).trim();
	if(!path.equals("error")){
		int s = path.indexOf("\"") + 1;
		int w = path.lastIndexOf("\"");
		path = path.substring(s,w);
	}
	
	//主要部分  end
	System.out.println("缩略图地址：" + path);
 }
}        